package com.mdinfo.gw.door.driver.aopu;


import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by Administrator on 2018/1/31.
 * 奥普门禁连接
 */
public class AopuClient {

    private String host;
    private Integer post;
    private EventLoopGroup group;
    private Bootstrap bootstrap;
    private Channel channel;
    private AopuReadOpration readOpration;
    private Logger logger = LoggerFactory.getLogger(AopuClient.class);

    public AopuClient(String host, Integer post, EventLoopGroup group,AopuReadOpration readOpration){
        this.host = host;
        this.post = post;
        this.group = group;
        this.readOpration = readOpration;
        init();
    }

    /**
     * 初始化
     */
    private void init(){
        bootstrap = new Bootstrap();
        AopuClient client = this;
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new AopuDoorHandlerAdapter(client,readOpration));
                    }
                });
        doConn();
    }

    /**
     * 连接服务端
     */
    public void doConn(){
        if(channel!=null && channel.isActive()){
            return;
        }

        if(channel!=null && !channel.isActive()){
           channel.closeFuture();
        }

        ChannelFuture future = bootstrap.connect(host, post);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture futureListener) throws Exception {
                if(futureListener.isSuccess()){
                    channel = futureListener.channel();
                    logger.info("连接澳普门禁控制器成功!");
                }else{
                    logger.info("连接澳普门禁控制器失败,30秒后重试...");
                    futureListener.channel().eventLoop().schedule(()->{
                        doConn();
                    },30, TimeUnit.SECONDS);
                }
            }
        });
    }


    /**
     * 发送数据
     */
    public void sendData(byte[] bytes){
        if(channel==null || !channel.isActive()){
            return;
        }
        ByteBuf byteBuf = Unpooled.copiedBuffer(bytes);
        ChannelFuture future = channel.writeAndFlush(byteBuf);
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                if(channelFuture.isSuccess()){
                    logger.info("数据发送成功!");
                }else{
                    logger.info("数据发送失败...");
                }
            }
        });
    }

    public boolean isConn(){
        if(channel!=null && channel.isActive()){
            return true;
        }
        return false;
    }
}
